import {copyJson, isEmptyObject} from '../common/vue-expand-func'
import {menuRouter, otherRouter} from "./router";

/**
 * 检查权限
 * @param toAccess   需要的权限
 * @param userAccess 用户的权限
 * @return {boolean}
 */
export function checkAccess(toAccess, userAccess) {
  if (isEmptyObject(toAccess))
    return true

  if (isEmptyObject(userAccess)) {
    if (!localStorage.access) return false
    userAccess = JSON.parse(localStorage.access)
  }


  // 如果需要的权限传进来是 string
  if (typeof toAccess === "string") {
    for (let i in userAccess) {
      let access = userAccess[i]
      if (access === toAccess)
        return true
    }
  }

  // 如果需要的权限传进来是 Array
  if (Array.isArray(toAccess)) {
    for (let i in userAccess) {
      for (let j in toAccess) {
        if (userAccess[i] === toAccess[j]) {
          return true
        }
      }
    }
  }

  return false
}

/**
 * 根据权限获取有效路由列表
 * @param accessArr 用户的权限集合
 * @return {*}
 */
export function getRouterMenuList(accessArr) {
  let menuList = copyJson([otherRouter, ...menuRouter])

  for (let i = 0; i < menuList.length; i++) {
    let item = menuList[i]

    for (let index = 0; index < item.children.length; index++) {
      let menu = item.children[index]
      if (!menu.meta.access)
        continue
      if (!checkAccess(menu.meta.access, accessArr)) {
        item.children.splice(index, 1)
        index--
      }
    }

    if (isEmptyObject(item.children)) {
      menuList.splice(i, 1) // 子菜单为空，删除该父级菜单
      i--
    }
  }
  return menuList
}
